package org.example.demo.apiv2.sql;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Function;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.SelectItem;
import org.example.demo.apiv2.entity.AggregateEntity;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AggregateParser {

    /**
     * 构造jsqlparser的SelectItem对象
     *
     * @param aggregateEntity
     * @return
     */
    public static SelectItem<?> getAggregateSelectItem(AggregateEntity aggregateEntity) {
        // 获取聚合函数名称
        String aggregateFunctionName = aggregateEntity.getAggFunc();
        // 获取要聚合的列名
        List<Column> columnList = new ArrayList<>();
        Column column = FieldParser.getColumn(aggregateEntity.getField());
        columnList.add(column);

        // 创建Function对象
        Function function = new Function();
        function.setName(aggregateFunctionName);
        function.setParameters(columnList.toArray(new Expression[0]));

        // 创建SelectItem对象
        SelectItem<?> selectItem = new SelectItem<>(function);
        return selectItem;
    }


    /**
     * 根据聚合函数字段，构造jsqlparser的SelectItem对象集合
     *
     * @param aggregateEntityList
     * @return
     */
    public static List<SelectItem<?>> getAggregateSelectItemList(List<AggregateEntity> aggregateEntityList) {
        if (CollectionUtil.isEmpty(aggregateEntityList)) {
            return new ArrayList<>();
        }
        List<SelectItem<?>> selectItemList = new ArrayList<>();
        for (AggregateEntity aggregateEntity : aggregateEntityList) {
            SelectItem<?> aggregateSelectItem = getAggregateSelectItem(aggregateEntity);
            selectItemList.add(aggregateSelectItem);
        }
        return selectItemList;
    }
}
